package bean.managed;

import entity.PasswordChangeRequest;
import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.PasswordChangeRequestFacade;

import entity.PersonEntity;
import exception.ContactNumberMismatchException;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
import util.Mailer;
import util.PasswordEncryptor;
import util.SecureRandomNumberGenerator;

@ManagedBean(name = "passwordChangeRequestController")
@RequestScoped
public class PasswordChangeRequestController implements Serializable {

    private PasswordChangeRequest current;
    private DataModel items = null;
    @EJB
    private bean.session.PasswordChangeRequestFacade ejbFacade;
    @EJB
    private bean.session.PersonEntityFacade personFacade;
    @EJB
    private bean.session.UserSettingEntityFacade settingFacade;
    @EJB
    private bean.session.PasswordChangeRequestFacade passwordFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    
    @ManagedProperty(value="#{salesLeadEntityController}")
    private SalesLeadEntityController salesLeadEntityController;
    
    @ManagedProperty(value="#{customerEntityController}")
    private CustomerEntityController customerEntityController;
    
    private String newPassword;
    private String passwordChangeRequestEmail;
    private String contactNumber;

    public PasswordChangeRequestController() {
    }

    public PasswordChangeRequest getSelected() {
        if (current == null) {
            current = new PasswordChangeRequest();
            selectedItemIndex = -1;
        }
        return current;
    }

    private PasswordChangeRequestFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }

    public String prepareView() {
        current = (PasswordChangeRequest) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new PasswordChangeRequest();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PasswordChangeRequestCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (PasswordChangeRequest) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PasswordChangeRequestUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (PasswordChangeRequest) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PasswordChangeRequestDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = PasswordChangeRequest.class)
    public static class PasswordChangeRequestControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            PasswordChangeRequestController controller = (PasswordChangeRequestController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "passwordChangeRequestController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof PasswordChangeRequest) {
                PasswordChangeRequest o = (PasswordChangeRequest) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + PasswordChangeRequestController.class.getName());
            }
        }
    }

    public String getNewPassword() {
        return newPassword;
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public String resetPassword() {
        try {
            String hashId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("hashId").toString();
            System.out.println("hashId from request: " + hashId);
            if (!passwordFacade.isRequestValid(passwordChangeRequestEmail, hashId)) {
                JsfUtil.addErrorMessage("invalid request. Please try again.");
            } else {
                PersonEntity person = personFacade.getPersonByEmail(passwordChangeRequestEmail);
                if(!contactNumber.equals(person.getContact().getContactNumber()))
                    throw new ContactNumberMismatchException("Wrong contact number!");
                person.setPassword(PasswordEncryptor.encryptPassword(newPassword));
                JsfUtil.addSuccessMessage("Password changed successfully");
                personFacade.edit(person);
                passwordFacade.markUsed(hashId);
            }
        }catch (ContactNumberMismatchException e) {
            JsfUtil.addErrorMessage(e, e.getMessage());
            e.printStackTrace();
        } 
        catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Reset password failed! Please contact system administrator");
            e.printStackTrace();
        }
        newPassword = null;
        passwordChangeRequestEmail = null;
        contactNumber = null;

        return "/index";
    }

    public String getPasswordChangeRequestEmail() {
        return passwordChangeRequestEmail;
    }

    public void setPasswordChangeRequestEmail(String passwordChangeRequestEmail) {
        this.passwordChangeRequestEmail = passwordChangeRequestEmail;
    }

    public String getContactNumber() {
        return contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

    public CustomerEntityController getCustomerEntityController() {
        return customerEntityController;
    }

    public void setCustomerEntityController(CustomerEntityController customerEntityController) {
        this.customerEntityController = customerEntityController;
    }

    public SalesLeadEntityController getSalesLeadEntityController() {
        return salesLeadEntityController;
    }

    public void setSalesLeadEntityController(SalesLeadEntityController salesLeadEntityController) {
        this.salesLeadEntityController = salesLeadEntityController;
    }
    
    public String forgetPasswordForwardToViewAccount(){
        forgetPassword();
        return "/entities/systemUserEntity/View?faces-redirect=true";
    }
    
    public String forgetPasswordForwardToSalesLeadList(){
        forgetPassword();
        return salesLeadEntityController.prepareList();
    }
    
    public String forgetPasswordForwardToAddAddresses(){
        forgetPassword();
        return customerEntityController.prepareAddress();
    }

    public void forgetPassword() {
        String hash = SecureRandomNumberGenerator.nextSecureRandomNumber();
        PasswordChangeRequest p = new PasswordChangeRequest();
        p.setEmail(passwordChangeRequestEmail);
        p.setHashedId(hash);
        passwordFacade.create(p);
        System.out.println("generated hash: " + hash);

        HttpServletRequest request = (HttpServletRequest) (FacesContext.getCurrentInstance().getExternalContext().getRequest());
        String base = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        String context = "/MacTeam-war/ForgetPassword.xhtml?hashId=" + hash;
        System.out.println("generated url: " + base + context);

        String content = "Click following link to reset password: " + base + context;
        try {
            Mailer.doSend("staff.merlion@gmail.com", passwordChangeRequestEmail, "",
                    "[Merlion] Reset Password", content, null, "");
            JsfUtil.addSuccessMessage("Please check your email.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        passwordChangeRequestEmail = null;
    }

}
